<template>
  <van-nav-bar
    title="注册"
    left-text="返回"
    left-arrow
    @click-left="router.go(-1)"
  />
  <van-form @submit="onSubmit" class="xl:w-[40%] xl:m-auto xl:mt-4">
    <van-cell-group inset>
      <van-field
        label-width="1.2rem"
        v-model="form.nickName"
        name="昵称"
        label="昵称"
        placeholder="昵称"
        :rules="[{ required: true, message: '请填写昵称' }]"
      />
      <van-field
        label-width="1.2rem"
        v-model="form.phone"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[{ validator, required: true, message: '请填写手机号' }]"
      />

      <van-field
        label-width="1.2rem"
        v-model="form.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field name="switch" label="性别" label-width="1.2rem">
        <template #input>
          <van-radio-group v-model="form.gender" class="w-full flex">
            <van-radio class="mr-1" name="1">男</van-radio>
            <van-radio name="0">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        name="头像"
        label="头像"
        label-width="1.2rem"
        :rules="[{ required: true, message: '请上传头像' }]"
      >
        <template #input>
          <van-uploader
            :preview-options="{
              closeable: true,
            }"
            :max-count="1"
            v-model="fileList"
            :after-read="afterRead"
            @delete="deleteImg"
          />
        </template>
      </van-field>
    </van-cell-group>

    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        立即注册
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import { Toast } from "vant";
import "vant/es/toast/style";
import { ref } from "vue-demi";
import { register, uploadfiles } from "@/api/login.js";
import router from "@/router/index.js";
const afterRead = (file) => {
  var formData = new FormData();
  formData.append("file", file.file);
  uploadfiles(formData).then((res) => {
    const { url } = res;
    // fileList.value = [url];
    form.value.avatarUrl = url;
  });
};
const onSubmit = () => {
  register(form.value).then((res) => {
    if (res) {
      Toast.success("注册成功,请登录");
      setTimeout(() => {
        router.push("/login");
      }, 1000);
    }
  });
};
const deleteImg = () => {
  form.value.avatarUrl = "";
};
const fileList = ref([]);
// 校验函数返回 true 表示校验通过，false 表示不通过
const validator = (val) => /^(?:(?:\+|00)86)?1\d{10}$/.test(val);

const form = ref({
  phone: "",
  password: "",
  nickName: "",
  avatarUrl: "",
  type: 101,
  gender: "1",
});
</script>

<style lang="scss" scoped>
</style>